<?php

class AdilityComponent extends Object
{    
    var $BASE_URL = "https://testapi.offersdb.com/distribution/beta/";
    
    var $key      = 'a66e356e01ef684c86af1e4639523686';
    
    var $components = array('Http');
    
    function __construct()
    {
        if(Configure::read('adility.is_test'))
        {
            $this->BASE_URL = 'https://testapi.offersdb.com/distribution/beta/';
            $this->key      = Configure::read('adility.key_test');
        }
        else
        {
            $this->BASE_URL = 'https://offersdb.com/distribution/beta/';
            $this->key      = Configure::read('adility.key_live');
        }
        
    }
    
    function _request($request,$arguments_post= array()) 
    {
        set_time_limit(0);
        $url    =  $this->BASE_URL . $request;
        
    	/* Connection timeout */
    	$this->Http->timeout=0;
    	/* Data transfer timeout */
    	$this->Http->data_timeout=0;
    	/* Output debugging information about the progress of the connection */
    	//$this->Http->debug=1;
    	/* Format dubug output to display with HTML pages */
        $this->Http->user_agent="Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)";
        $this->Http->follow_redirect=1;
        $this->Http->redirection_limit=5;
        $this->Http->exclude_address="";
        $this->Http->prefer_curl=0;
        //$this->Http->force_multipart_form_post= true;
        //ducnha code here
        $this->Http->accept  = "Accept: application/json";
    	$error         = $this->Http->GetRequestArguments($url,$arguments);
        //ducnha code here
        $arguments["Headers"]["X-OFFERSDB-API-KEY"] = $this->key;
        $arguments["Headers"]["Pragma"]="nocache";
        $arguments["Headers"]["Content-Type"]="application/json";
        $arguments = array_merge($arguments,$arguments_post);
        //3370a4265e221d9c5b480c4791eef98f
       
    	$error=$this->Http->Open($arguments);
        $t = "";
        if($error=="")
    	{
    		$error=$this->Http->SendRequest($arguments);
        	if($error=="")
    		{
        		$headers=array();
    			$error=$this->Http->ReadReplyHeaders($headers);
                //print_r($headers);
    			if($error=="")
    			{
    				for(;;)
    				{
    					$error=$this->Http->ReadReplyBody($body,1000);
					    if($error!="" || strlen($body)==0)
    						break;
					    $t .= $body;
    				}
    		    }
    		}
    		$this->Http->Close();
    	}
        return json_decode($t);
    }
    function GetDealById($deal_id)
    {
        $t = $this->_request('offers/'.$deal_id.'.json');
        if($t->status=='ERROR')
        {
            return false;
        }   
        $t = $t->offer;      
        
        $deal                   = array();
        $company                = array();
        $deal_type              = array();
        //print_r($t);exit;
        $deal['id']             = $t->id;
        $deal['user_id']        = 1;
        $deal['name']           = $t->title;
        $deal['description']    = $t->creative->description.' ';
        $deal['image']          = $t->creative->illustrations[0]->url;
        $deal['original_price'] = $t->value->amount/100;
        $deal['discount_percentage']= ($t->value->amount-$t->price->amount)*100/$t->value->amount;  
        $deal['savings']            = ($t->value->amount - $t->price->amount) / 100;
        $deal['discounted_price']   = $t->price->amount/100;
        $deal['quantity_in_stock']  = $t->quantity_in_stock;
        $deal['min_limit']                  = 1;
        $deal['max_limit']                  = $t->quantity_in_stock;
        $deal['buy_min_quantity_per_user']  = 1;
        $deal['buy_max_quantity_per_user']  = $t->quantity_in_stock;
        $deal['start_date']         = $t->start_date;
        $deal['end_date']           = $t->end_date;
        $deal['fine_print']         = $t->fine_print.' ';
        $deal['reviews']             = $t->advertiser->reviews;
        
        $company['address1']        = $t->advertiser->redemption_locations[0]->address_line_1;
        $company['City']['name']    = $t->advertiser->redemption_locations[0]->city;
        $company['Country']['name'] = $t->advertiser->redemption_locations[0]->country_code;
        
        $deal_type['type']          = 1;
        $deal_type['api_id']        = $t->id;
        
        $data['Deal']               = $deal;
        $data['Company']            = $company;
        $data['DealType']           = $deal_type;
        return $data;
    }
    
    function ListDeal($city_name,$state,$page,$category_param,$what_deals_param,$per_page=10)
    {
        $city_name  = str_ireplace('-city','',$city_name);
        $city_name  = str_ireplace('city','',$city_name);
        $request = "offers.json?city={$city_name}&state={$state}&distance=100&per_page={$per_page}&page={$page}{$category_param}{$what_deals_param}";
        
        return $this->_request($request);
    }
    
    function CreateOrder($id,$quantity=1,$order,$has_shipping_address=false)
    {        
        $items              = array();
        $shipping_address   = array(
                                    'address_1' => $order['address'],
                                    'address_2' => $order['address2'],
                                    'city'      => $order['city'],
                                    'state'     => $order['state'],
                                    'zip_code'  => $order['zip_code'],
                                    );
        $items[]            = array(
                                    'offer_id'  => $id,
                                    'quantity'  => $quantity,
                                    );
                        
        $post               = array(
                                    'order_number'      => 'dealuser_'.$order['id'],
                                    'customer_name'     => $order['realname'],
                                    //'account_id'        => $order['user_id'],
                                    'items'             => $items,
                                    );
        if($has_shipping_address)
        {
            $post['shipping_address']       = $shipping_address;
        }
        
        $post   = array('order'=>$post);
        $post   = json_encode($post);
        return $this->_request('orders.json',array('RequestMethod'=>'POST','BodyStream'=>true,'Body'=>$post));
        
        
    }
    /**
     * status: active, cancelled,
     */
    function ListOrders($start_date,$end_date,$status,$page=1,$per_page=10)
    {
        $search_params    = 'start_date='.$start_date.'&end_date='.$end_date.'&status='.$status.'&page='.$page.'&per_page='.$per_page;
        return $this->_request('orders.json?{$search_params}');
    }
    
    function GetOrder($order_id)
    {
        return $this->_request('orders/'.$order_id.'.json');
    }
    
    function CancelOrder($order_id)
    {
        $post   = array('order'=>array('status'=>'cancelled'));
        $post   = json_encode($post);
        return $this->_request('orders/'.$order_id.'.json',array('RequestMethod'=>'PUT','BodyStream'=>true,'Body'=>$post));
    }
    
    function createAccount($name,$website)
    {
        $post   = array('name'=> $name,'website_url'=> $website);
        $post   = array('account'=>$post);
        $post   = json_encode($post);
        return $this->_request('accounts.json',array('RequestMethod'=>'POST','BodyStream'=>true,'Body'=>$post));
    }
    
    function ClipCoupon($offer_id)
    {
        $post   = array('clip'=>'');
        $post   = json_encode($post);
        return $this->_request('offers/'.$offer_id.'/clips',array('RequestMethod'=>'POST','BodyStream'=>true,'Body'=>$post));
    }
}
?>